package com.creative.accountsdk.letter;

import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.Toast;

import com.creative.accountsdk.R;
import com.creative.accountsdk.widget.CustomDialog;

public class SortAdapter extends BaseAdapter implements SectionIndexer{
	/** 屏幕宽度 */
	private int mScreenWidth;

	/** 删除按钮事件 */
	private DeleteButtonOnclickImpl mDelOnclickImpl;
	/** HorizontalScrollView左右滑动事件 */
	private ScrollViewScrollImpl mScrollImpl;
	/** 布局参数,动态让HorizontalScrollView中的TextView宽度包裹父容器 */
	private LinearLayout.LayoutParams mParams;

	/** 记录滑动出删除按钮的itemView */
	public HorizontalScrollView mScrollView;

	/** touch事件锁定,如果已经有滑动出删除按钮的itemView,就屏蔽下一整次(down,move,up)的onTouch操作 */
	public boolean mLockOnTouch = false;
	CustomDialog dialog;

	private List<SortModel> list = null;
	private Context mContext;
	
	public SortAdapter(Context mContext, List<SortModel> list) {
		this.mContext = mContext;
		this.list = list;

		// 搞到屏幕宽度
		Display defaultDisplay = ((Activity) mContext).getWindowManager()
				.getDefaultDisplay();
		DisplayMetrics metrics = new DisplayMetrics();
		defaultDisplay.getMetrics(metrics);

		mScreenWidth = metrics.widthPixels;
		mParams = new LinearLayout.LayoutParams(mScreenWidth,
				LinearLayout.LayoutParams.MATCH_PARENT);

		// 初始化删除按钮事件与item滑动事件
		mDelOnclickImpl = new DeleteButtonOnclickImpl();
		mScrollImpl = new ScrollViewScrollImpl();
	}
	
	/**
	 * 当ListView数据发生变化时,调用此方法来更新ListView
	 * @param list
	 */
	public void updateListView(List<SortModel> list){
		this.list = list;
		notifyDataSetChanged();
	}

	public int getCount() {
		return this.list.size();
	}

	public Object getItem(int position) {
		return list.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(final int position, View view, ViewGroup arg2) {
		ViewHolder viewHolder = null;
		final SortModel mContent = list.get(position);
		if (view == null) {
			viewHolder = new ViewHolder();
			view = LayoutInflater.from(mContext).inflate(R.layout.letter_item, null);

			viewHolder.slSildeDelete =  (HorizontalScrollView)view.findViewById(R.id.sc_silde_delete);
			viewHolder.slSildeDelete.setOnTouchListener(mScrollImpl);
			viewHolder.slSildeDelete.setTag(position);

			viewHolder.tvTitle = (TextView) view.findViewById(R.id.tv_letter_title);
			viewHolder.tvTitle.setLayoutParams(mParams);
			viewHolder.tvLetter = (TextView) view.findViewById(R.id.tv_letter_catalog);

			// 设置item内容为fill_parent的
			viewHolder.deleteButton = (Button) view.findViewById(R.id.item_delete);
			viewHolder.deleteButton.setOnClickListener(mDelOnclickImpl);


			view.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) view.getTag();
		}
		
		//根据position获取分类的首字母的Char ascii值
		int section = getSectionForPosition(position);
		
		//如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
		if(position == getPositionForSection(section)){
			viewHolder.tvLetter.setVisibility(View.VISIBLE);
			viewHolder.tvLetter.setText(mContent.getSortLetters());
		}else{
			viewHolder.tvLetter.setVisibility(View.GONE);
		}

		viewHolder.position = position;
		viewHolder.deleteButton.setTag(viewHolder);
		viewHolder.slSildeDelete.scrollTo(0, 0);
		viewHolder.tvTitle.setText(this.list.get(position).getName());
		
		return view;
	}
	


	final static class ViewHolder {
		HorizontalScrollView slSildeDelete;
		TextView tvLetter;
		TextView tvTitle;
		Button deleteButton;
		int position;
	}


	/**
	 * 根据ListView的当前位置获取分类的首字母的Char ascii值
	 */
	public int getSectionForPosition(int position) {
		return list.get(position).getSortLetters().charAt(0);
	}

	/**
	 * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
	 */
	public int getPositionForSection(int section) {
		for (int i = 0; i < getCount(); i++) {
			String sortStr = list.get(i).getSortLetters();
			char firstChar = sortStr.toUpperCase().charAt(0);
			if (firstChar == section) {
				return i;
			}
		}
		
		return -1;
	}
	
	/**
	 * 提取英文的首字母，非英文字母用#代替。
	 * 
	 * @param str
	 * @return
	 */
	private String getAlpha(String str) {
		String  sortStr = str.trim().substring(0, 1).toUpperCase();
		// 正则表达式，判断首字母是否是英文字母
		if (sortStr.matches("[A-Z]")) {
			return sortStr;
		} else {
			return "#";
		}
	}

	@Override
	public Object[] getSections() {
		return null;
	}


	/** HorizontalScrollView的滑动事件 */
	private class ScrollViewScrollImpl implements View.OnTouchListener {
		/** 记录开始时的坐标 */
		private float startX = 0;
        private boolean isSlide = false;
		@SuppressLint("ClickableViewAccessibility")
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					// 如果有划出删除按钮的itemView,就让他滑回去并且锁定本次touch操作,解锁会在父组件的dispatchTouchEvent中进行
					if (mScrollView != null) {
						scrollView(mScrollView, HorizontalScrollView.FOCUS_LEFT);
						mScrollView = null;
						mLockOnTouch = true;
						return true;
					}
					startX = event.getX();
					break;
				case MotionEvent.ACTION_UP:
					HorizontalScrollView view = (HorizontalScrollView) v;
					// 如果滑动了>50个像素,就显示出删除按钮
					if (startX > event.getX() + 50) {
						startX = 0;// 因为公用一个事件处理对象,防止错乱,还原startX值
						scrollView(view, HorizontalScrollView.FOCUS_RIGHT);
						mScrollView = view;
						isSlide = true;
					} else {
						if(isSlide){
							scrollView(view, HorizontalScrollView.FOCUS_LEFT);
							isSlide = false;
						}else{
							final int position =(int)v.getTag();
							dialog(position);
						}
					}
					break;
			}
			return false;
		}
	}

	/** HorizontalScrollView左右滑动 */
	public void scrollView(final HorizontalScrollView view, final int parameter) {
		view.post(new Runnable() {
			@Override
			public void run() {
				view.pageScroll(parameter);
			}
		});
	}
	/** 滑动删除事件 */
	private class DeleteButtonOnclickImpl implements View.OnClickListener {
		@Override
		public void onClick(View v) {
			final ViewHolder holder = (ViewHolder) v.getTag();
			Toast.makeText(mContext, "删除" + holder.position + "项", Toast.LENGTH_SHORT).show();
			Animation animation = AnimationUtils.loadAnimation(mContext,
					R.anim.anim_item_delete);
			holder.slSildeDelete.startAnimation(animation);
			animation.setAnimationListener(new Animation.AnimationListener() {
				@Override
				public void onAnimationStart(Animation animation) {
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationEnd(Animation animation) {
					//remove(getItem(holder.position));
				}
			});

		}
	}

	// 弹窗
	private void dialog(final int position) {
		dialog = new CustomDialog(mContext);
		EditText editText = (EditText) dialog.getEditText();//方法在CustomDialog中实现
		editText.setText(position+"");
		dialog.setOnPositiveListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();

			}
		});
		dialog.setOnNegativeListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.show();
	}

}
